#!/usr/bin/env python

import urllib
import os
import random

def crt_endnum(num,PGnum):
	if len(str(num)) == len(PGnum):
		return str(num)
	elif len(str(num)) < len(PGnum):
		return ('0'*(len(PGnum)-len(str(num))))+str(num)
	else:
		raise Exception("Page number Error!\n")

class download:

	def __init__(self,down_info,save_prefix='.'):
		self.down_info	= down_info
		self.save_prefix = save_prefix
		#self.save_name_lst = list()
		
	def gen_save_dir(self):
		if os.path.abspath(self.save_prefix) != os.path.abspath( os.getcwd() ):
			if not os.path.exists(self.save_prefix):
				os.mkdir(self.save_prefix)
			else:
				tmp=self.save_prefix+''.join(map(chr,[random.randint(65,65+26) for i in range(6)]))
				while os.path.exists(tmp):
					tmp=self.save_prefix+''.join(map(chr,[random.randint(65,65+26) for i in range(6)]))

				os.mkdir(tmp)
				self.save_prefix=tmp


	def fetch_save_dir(self):
		#self.gen_save_dir()
		return self.save_prefix

	def run(self):
		self.gen_save_dir()
		#self.save_name_lst = list()
		for i in range(1,int(self.down_info['totalpage'])+1):
			down_hdl= urllib.urlopen(self.down_info["downHead"]+crt_endnum(i,self.down_info['totalpage'])+'.'+self.down_info['extname'])
			file_name = crt_endnum(i,self.down_info['totalpage'])+'.'+self.down_info['extname']
			full_name = os.path.join(self.save_prefix,file_name)
			down_file = open(full_name,'w')
			down_file.write(down_hdl.read())
			down_file.close()
			#self.save_name_lst.append(full_name)
			print full_name 




